#define INA 7  //定义引脚控制左边电机方向
#define ENA 6  //控制左边电机速度
#define INB 8  //右边电机方向
#define ENB 5  //右边电机速度

#define wayPin1 9
#define wayPin2 10
boolean L_tval = 0;
boolean R_tval = 0;

void setup() {
  Serial.begin(9600);   //设置串口波特率
  pinMode(INA, OUTPUT);  //设置控制电机的引脚为输出模式
  pinMode(ENA, OUTPUT);
  pinMode(INB, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(wayPin1, INPUT);
  pinMode(wayPin2, INPUT);
}

void loop() {
  car_tracking();
}

void car_tracking()
{
  L_tval = digitalRead(wayPin1);
  R_tval = digitalRead(wayPin2);
  Serial.print(L_tval);
  Serial.print("  ");
  Serial.println(R_tval);
  //delay(100);
  if((L_tval == 1) && (R_tval == 1))
  {
    car_forward();
  }
  else if((L_tval == 1) && (R_tval == 0))
  {
    car_left();
  }
  else if((L_tval == 0) && (R_tval == 1))
  {
    car_right();
  }
  else if((L_tval == 0) && (R_tval == 0))
  {
    car_stop();
  }
}

//小蜗牛前进
void car_forward()
{
  digitalWrite(INA, HIGH);  //输出高电平，控制左边电机正转
  analogWrite(ENA, 50);    //PWM输出，控制左边电机速度
  digitalWrite(INB, HIGH);  //右边电机正转
  analogWrite(ENB, 50);    //右边电机速度
}

//小蜗牛左转
void car_left()
{
  digitalWrite(INA, LOW);
  analogWrite(ENA, 80);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 130);
}
//小蜗牛右转
void car_right()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 130);
  digitalWrite(INB, LOW);
  analogWrite(ENB, 80);
}
//停止
void car_stop()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 0);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 0);
}
